//
//  LHHomeViewModel.swift
//  LH-Swift-WeiBo
//
//  Created by liuhao on 16/9/27.
//  Copyright © 2016年 liuhao. All rights reserved.
//

import UIKit

class LHHomeViewModel: NSObject {
    
    
    lazy var viewModelArray : [LHStatusViewModel] = [LHStatusViewModel]()
    
    //加载数据方法 闭包但会加载数据的结果
    func loadData(finished : @escaping (Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let paramters = ["access_token" : LHUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token ?? ""]
        
        //通过网络工具类发送请求
        LHNetWorktools.sharedTools.request(method: .GET, urlString: urlString, parameters: paramters) { (responseObiect, error) in
            //判断是否成功
            if error != nil {
                finished(false)
                return
            }
            
            //数据请求成功加载数据
            //解析数据  转换字典数据,类型转换  字典转模型
            let dict = responseObiect as! [String :Any]
            
            //在字典中取statuses
            guard let Array = dict["statuses"] as? [[String : Any]] else {
                
                finished(false)
                return
            }
            
            //遍历数组  字典转模型 添加到数组中
            for item in Array {
                
                let ViewModel = LHStatusViewModel()
                let status = LHStatus()
                
                status.yy_modelSet(with: item)
                ViewModel.status = status
                
                self.viewModelArray.append(ViewModel)
            }
            
            finished(true)
        }
        
    }
    
}
